import React, { useState, useEffect } from 'react';
import { Form, Table, Tag, Input } from 'antd';
import { dictionaryList } from '@/services/dictionary';
import ColorPicker from '@/components/ColorPicker';
import Difference from '@/pages/WorkFlow/components/FormControls/components/Difference';
import { BaseWrapper } from '@/pages/Organization/OrgFlow/components';
import { size } from 'lodash';
import { genID } from '@/pages/WorkFlow/utils';
import FileUpload from '@/components/Custom/FileUpload';
import CityPicker from '@/components/CityPicker';

const { TextArea } = Input;
// const { Option } = Select;

const ORGANIZATION_TYPE = {
    1: '集团',
    2: '公司',
    3: '部门',
    4: '事业部'
};

const CompanyEdit = ({ form, data, wrapperLayout }) => {
    // console.log('======>data', data);
    const { getFieldDecorator } = form;
    const { compareDataField, oldBusinessData, organizationType, resourceFile1, resourceFile2 } = data; // 数据源
    const orgTitle = ORGANIZATION_TYPE[organizationType]; // 集团公司名称映射
    const [isSingapore, setIsSingapore] = useState(false); // 是否是新加坡公司
    const [industryOptions, setIndustryOptions] = useState([]); // 所属行业字典
    const [compareDataMap, setCompareDataMap] = useState({}); // 差异化对比映射数据源（非表格）
    const [addrData, setAddrData] = useState(data?.addressDtoList || []); // 地址数据

    const { updateFieldNames, seniorUpdateContent = {} } = compareDataField;
    const { edit: addrEditData = [] } = seniorUpdateContent; // 编辑的数据

    const [logoFile, setLogoFile] = useState([]);
    const [licenseFile, setLicenseFile] = useState([]);

    // logo数据源
    useEffect(() => {
        if (size(resourceFile1) > 0) {
            const { urlList } = resourceFile1[0];
            if (size(urlList) > 0) {
                setLogoFile([
                    {
                        uid: urlList[0].keyName,
                        keyName: urlList[0].keyName,
                        name: urlList[0].originName,
                        oldName: urlList[0].originName,
                        url: urlList[0].url
                    }
                ]);
            }
        }
    }, [resourceFile1]);

    // 营业执照数据源
    useEffect(() => {
        if (size(resourceFile2) > 0) {
            const { urlList = [] } = resourceFile2[0];
            if (size(urlList) > 0) {
                setLicenseFile([
                    {
                        uid: urlList[0].keyName,
                        keyName: urlList[0].keyName,
                        name: urlList[0].originName,
                        oldName: urlList[0].originName,
                        url: urlList[0].url
                    }
                ]);
            }
        }
    }, [resourceFile2]);

    useEffect(() => {
        // 拉取行业字典
        const fetchDict = async () => {
            const { code, data: itData } = await dictionaryList({ codes: ['industryType'] });
            if (code === 10000) {
                setIndustryOptions(itData);
            }
        };
        fetchDict();
    }, []);

    useEffect(() => {
        // 将有变更的数据进行映射
        if (updateFieldNames && updateFieldNames?.length > 0) {
            const obj = {};
            updateFieldNames.forEach(item => {
                obj[item] = oldBusinessData[item];
            });
            setCompareDataMap(obj);
        }
    }, [updateFieldNames, oldBusinessData]);

    // 根据公司地址是否是新加坡修改状态
    useEffect(() => {
        if (data?.area?.includes('Singapore')) {
            setIsSingapore(true);
        } else {
            setIsSingapore(false);
        }
    }, [data?.area]);

    useEffect(() => {
        if (size(seniorUpdateContent) > 0) {
            setAddrData([...addrData, ...seniorUpdateContent?.delete]);
        }
    }, [seniorUpdateContent]);

    // 表格单元格是否修改
    const colChangeText = (record, rowuuid, field) => {
        if (record && rowuuid && field) {
            let obj = {};
            addrEditData.forEach(item => {
                const tempObj = JSON.parse(item);
                if (Object.keys(tempObj).includes(record[rowuuid])) {
                    obj = tempObj;
                }
            });
            const changeArr = Object.values(obj);
            const changeObj = changeArr.find(item => item[field]);
            if (changeObj) {
                return changeObj[field];
            }
            return undefined;
        }
        return undefined;
    };

    const columns = [
        {
            title: '名称',
            dataIndex: 'addressName',
            width: '20%',
            render: (text, record) => (
                <Difference table tip={colChangeText(record, 'addressCode', 'addressName')}>
                    {text}
                </Difference>
            )
        },
        {
            title: '所在地区',
            dataIndex: 'area',
            width: '30%',
            render: (text, record) => (
                <Difference
                    table
                    tipCover={
                        colChangeText(record, 'addressCode', 'area')?.split(',').length && (
                            <div style={{ display: 'flex' }}>
                                <span>原始值：</span>
                                <CityPicker
                                    showOnly
                                    valueType="code"
                                    value={
                                        colChangeText(record, 'addressCode', 'area')
                                            ?.split(',')
                                            .pop() || ''
                                    }
                                />
                            </div>
                        )
                    }
                >
                    <CityPicker showOnly valueType="codeArray" value={text?.split(',') || []} />
                </Difference>
            )
        },
        {
            title: '详细地址',
            dataIndex: 'addressDetail',
            render: (text, record) => {
                const { addressCode, isDefault } = record;
                return (
                    <Difference table tip={colChangeText(record, 'addressCode', 'addressDetail')}>
                        <span style={{ marginRight: 5 }}>{text}</span>
                        {isDefault ? (
                            <Tag color="orange" style={{ marginLeft: 10 }}>
                                通讯地址
                            </Tag>
                        ) : null}
                        {!addressCode && <Tag color="green">新增</Tag>}
                        {seniorUpdateContent?.delete?.find(item => item.addressCode === addressCode) && (
                            <Tag color="red">删除</Tag>
                        )}
                    </Difference>
                );
            }
        }
    ];

    return (
        <Form {...wrapperLayout}>
            <BaseWrapper title="基本信息">
                <Form.Item label={`${orgTitle}名称(中文)`}>
                    <Difference tip={compareDataMap?.organizationName}>
                        {getFieldDecorator('organizationName', {
                            initialValue: data?.organizationName
                        })(<Input disabled />)}
                    </Difference>
                </Form.Item>
                <Form.Item label={`${orgTitle}名称(英文)`}>
                    <Difference tip={compareDataMap?.organizationNameEnglish}>
                        {getFieldDecorator('organizationNameEnglish', {
                            initialValue: data?.organizationNameEnglish
                        })(<Input disabled />)}
                    </Difference>
                </Form.Item>
                {/* <Form.Item label="主管称呼">
                    <Difference tip={compareDataMap?.titleName}>
                        {getFieldDecorator('titleName', {
                            initialValue: data?.titleName
                        })(<Input disabled />)}
                    </Difference>
                </Form.Item> */}
                <Form.Item label="主题色">
                    <Difference
                        tipCover={
                            compareDataMap?.colorCode && (
                                <div style={{ display: 'flex' }}>
                                    原始值：
                                    <ColorPicker readOnly value={compareDataMap?.colorCode} />
                                </div>
                            )
                        }
                    >
                        {getFieldDecorator('colorCode', {
                            initialValue: data?.colorCode
                        })(<ColorPicker disabled />)}
                    </Difference>
                </Form.Item>

                {data?.organizationType !== 1 ? (
                    <>
                        <Form.Item label="排序号">
                            <Difference tip={compareDataMap?.sort}>
                                {getFieldDecorator('sort', {
                                    initialValue: data?.sort
                                })(<Input disabled />)}
                            </Difference>
                        </Form.Item>
                        {/* relativeList为上层传递下来的数组 */}
                        {/* <Form.Item label="是否助理团">
                            <Difference tip={compareDataMap?.assistantFlag}>
                                {getFieldDecorator('assistantFlag', {
                                    initialValue: data?.assistantFlag
                                })(
                                    <Radio.Group disabled>
                                        <Radio value={0}>否</Radio>
                                        <Radio value={1}>是</Radio>
                                    </Radio.Group>
                                )}
                            </Difference>
                        </Form.Item>

                        <Form.Item label="关联机构">
                            <Difference
                                tip={
                                    compareDataMap?.relateOrganizationCodes &&
                                    compareDataMap.relateOrganizationCodes.map(
                                        item => relativeList.find(x => x.organizationCode === item)?.organizationName
                                    )
                                }
                            >
                                {getFieldDecorator('relateOrganizationCodes', {
                                    initialValue: data?.relateOrganizationCodes
                                })(
                                    <Select mode="multiple" getPopupContainer={trigger => trigger.parentNode} disabled>
                                        {relativeList
                                            .filter(item => item.assistantFlag !== data?.assistantFlag)
                                            .map(item => (
                                                <Option value={item.organizationCode} key={item.organizationCode}>
                                                    {item.organizationName}
                                                    {item?.auditStatus === 1 && '(审批中)'}
                                                </Option>
                                            ))}
                                    </Select>
                                )}
                            </Difference>
                        </Form.Item> */}

                        <Form.Item label="上级机构">
                            <Difference tip={compareDataMap?.parentOrganizationName}>
                                {data?.parentOrganizationName}
                            </Difference>
                        </Form.Item>
                    </>
                ) : null}

                <Form.Item label="国家/地区">
                    <Difference
                        tipCover={
                            compareDataMap?.area && (
                                <div style={{ display: 'flex' }}>
                                    <span>原始值：</span>
                                    <CityPicker
                                        showOnly
                                        valueType="codeArray"
                                        value={compareDataMap?.area?.split(',') || []}
                                    />
                                </div>
                            )
                        }
                    >
                        {getFieldDecorator('area', {
                            initialValue: data?.area.split(',') || []
                        })(<CityPicker valueType="codeArray" disabled />)}
                    </Difference>
                </Form.Item>
                <Form.Item label={`${orgTitle}简介(中文)`}>
                    <Difference tip={compareDataMap?.organizationDesc}>
                        {getFieldDecorator('organizationDesc', {
                            initialValue: data?.organizationDesc
                        })(<TextArea disabled autosize={{ minRows: 3, maxRows: 6 }} maxLength={400} />)}
                    </Difference>
                </Form.Item>
                <Form.Item label={`${orgTitle}简介(英文)`}>
                    <Difference tip={compareDataMap?.organizationDescEnglish}>
                        {getFieldDecorator('organizationDescEnglish', {
                            initialValue: data?.organizationDescEnglish
                        })(<TextArea disabled autosize={{ minRows: 3, maxRows: 6 }} maxLength={400} />)}
                    </Difference>
                </Form.Item>
                <Form.Item label={`${orgTitle}logo`} style={{ marginBottom: 0, minHeight: 130 }}>
                    <FileUpload isSingle disabled value={{ allFileList: logoFile }} />
                </Form.Item>
            </BaseWrapper>

            <BaseWrapper title="其他信息">
                <Form.Item label="法人代表">
                    <Difference tip={compareDataMap?.legalRepresentative}>
                        {getFieldDecorator('legalRepresentative', {
                            initialValue: data?.legalRepresentative
                        })(<Input disabled />)}
                    </Difference>
                </Form.Item>
                <Form.Item label={isSingapore ? 'UEN' : '统一社会信用代码'}>
                    <Difference tip={compareDataMap?.licenseCode}>
                        {getFieldDecorator('licenseCode', {
                            initialValue: data?.licenseCode
                        })(<Input disabled />)}
                    </Difference>
                </Form.Item>
                <Form.Item
                    label={isSingapore ? 'UEN证件照片' : '营业执照照片'}
                    style={{ marginBottom: 0, minHeight: 130 }}
                >
                    <FileUpload isSingle disabled value={{ allFileList: licenseFile }} />
                </Form.Item>

                <Form.Item label="联系电话">
                    <Difference tip={compareDataMap?.phone}>
                        {getFieldDecorator('phone', {
                            initialValue: data?.phone
                        })(<Input disabled />)}
                    </Difference>
                </Form.Item>
                <Form.Item label="邮政编码">
                    <Difference tip={compareDataMap?.postalcode}>
                        {getFieldDecorator('postalcode', {
                            initialValue: data?.postalcode
                        })(<Input disabled />)}
                    </Difference>
                </Form.Item>
                <Form.Item label="官网地址">
                    <Difference tip={compareDataMap?.websiteAddress}>
                        {getFieldDecorator('websiteAddress', {
                            initialValue: data?.websiteAddress
                        })(<Input disabled />)}
                    </Difference>
                </Form.Item>
                <Form.Item label="所属行业">
                    <Difference
                        tip={
                            compareDataMap?.industry &&
                            (industryOptions.find(item => item.dictValue === String(compareDataMap?.industry))
                                ?.dictName ||
                                '')
                        }
                    >
                        {getFieldDecorator('industry', {
                            initialValue: industryOptions.find(item => item.dictValue === String(data?.industry))
                                ?.dictName
                        })(<Input disabled />)}
                    </Difference>
                </Form.Item>
                <Form.Item label="经营范围(中文)">
                    <Difference tip={compareDataMap?.business}>
                        {getFieldDecorator('business', {
                            initialValue: data?.business
                        })(<TextArea disabled autosize={{ minRows: 3, maxRows: 10 }} maxLength={10000} />)}
                    </Difference>
                </Form.Item>

                <Form.Item label="经营范围(英文)">
                    <Difference tip={compareDataMap?.businessEnglish}>
                        {getFieldDecorator('businessEnglish', {
                            initialValue: data?.businessEnglish
                        })(<TextArea disabled autosize={{ minRows: 3, maxRows: 10 }} maxLength={20000} />)}
                    </Difference>
                </Form.Item>

                {data?.organizationType === 1 ? (
                    <Form.Item label="注册邮箱">
                        <Difference tip={compareDataMap?.email}>
                            {getFieldDecorator('email', {
                                initialValue: data?.email
                            })(<Input disabled />)}
                        </Difference>
                    </Form.Item>
                ) : null}

                <Form.Item label="创建时间">
                    <Difference tip={compareDataMap?.regTime}>
                        {getFieldDecorator('regTime', {
                            initialValue: data?.regTime
                        })(<Input disabled />)}
                    </Difference>
                </Form.Item>
                <BaseWrapper title="办公地点">
                    <Table
                        bordered={false}
                        columns={columns}
                        dataSource={addrData}
                        pagination={false}
                        rowKey={genID(6)}
                    />
                </BaseWrapper>
                <br />
                <BaseWrapper title="财务信息">
                    <Form.Item label="默认结算货币">
                        <Difference
                            tip={`${compareDataMap?.currencyCode}${
                                compareDataMap?.currencyText ? `（${compareDataMap?.currencyText}）` : ''
                            }`}
                        >
                            {getFieldDecorator('currencyCode', {
                                initialValue: `${data?.currencyCode}（${data?.currencyText}）`
                            })(<Input disabled />)}
                        </Difference>
                    </Form.Item>
                </BaseWrapper>
            </BaseWrapper>
        </Form>
    );
};

export default Form.create()(CompanyEdit);
